package com.zuimei.zuimei.fragments;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.zuimei.zuimei.R;
import com.zuimei.zuimei.adapters.Item4RecycleViewItemAdapter;
import com.zuimei.zuimei.base.BaseFragment;
import com.zuimei.zuimei.beans.FindAppItem4Bean;
import com.zuimei.zuimei.jsonutil.ParseFindAppJson;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import butterknife.Bind;

/**
 * Created by Jogger on 2017/1/16.
 * 发现应用viewpager内fragment
 */

public class FindAppItem4Fragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener{
    @Bind(R.id.rv_item)
    RecyclerView rv_item;
    @Bind(R.id.srl_refresh)
    SwipeRefreshLayout srl_refresh;
    private List<FindAppItem4Bean> mContentList;
    private Item4RecycleViewItemAdapter mAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.rv_find_app_item;
    }

    @Override
    public void loadData() {
        srl_refresh.setOnRefreshListener(this);
        String jsonData = getJsonData();
        mContentList =ParseFindAppJson.getItem4List(jsonData);
        rv_item.setLayoutManager(new GridLayoutManager(mActivity, 2));
        mAdapter = new Item4RecycleViewItemAdapter(mActivity);
        rv_item.setAdapter(mAdapter);
        mAdapter.loadData(mContentList);
    }

    /**
     * 获取json数据
     */
    private String getJsonData() {
        String result = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            is = mActivity.getResources().getAssets().open("collectjson");
            baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int ret;
            while ((ret = is.read(buf, 0, buf.length)) != -1) {
                baos.write(buf, 0, ret);
            }
            result = baos.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public void onRefresh() {
        mAdapter.notifyDataSetChanged();
        srl_refresh.setRefreshing(false);
    }
}
